﻿using QxFramework.Core;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using GameMap;
using System;

public class BagObjectPanel : UIBase
{
    public List<Tuple<GameObject, CombinableItemField>> BagItemsList = new List<Tuple<GameObject, CombinableItemField>>();
    GridLayoutGroup gridBag;
    GameObject BasementBag;

    void Awake()
    {
        this.transform.parent.GetComponent<UIBase>().Get<Button>("Up").onClick.SetListener(UpPage);
        this.transform.parent.GetComponent<UIBase>().Get<Button>("Down").onClick.SetListener(DownPage);

        gridBag = this.GetComponent<GridLayoutGroup>();

        BagItemsList.Add(new Tuple<GameObject, CombinableItemField> ( transform.Find("BagObjectBasement").gameObject,null));

        pageText = transform.parent.Find("FlipBagPagePanel").Find("Text").GetComponent<Text>();
        GenBagTable();
        MessageManager.Instance.Get<ItemMapEvent>(false).RegisterHandler(ItemMapEvent.BenchToBag, BenchToBag);
        MessageManager.Instance.Get<ItemMapEvent>(false).RegisterHandler(ItemMapEvent.BagToBench, BagToBench);

    }
    int bagCurrentPage;
    int bagCntInRow;
    int bagTotalPage;
    Text pageText;
    void UpPage()
    {
       RefreshBag(bagCurrentPage - 1);
        CombineUI.Instance.ChangeSelectedObject(null);
    }
    void DownPage()
    {
        RefreshBag(bagCurrentPage + 1);
        CombineUI.Instance.ChangeSelectedObject(null);
    }
    /*  void BagObjectOnClick(string id)
      {
          Debug.Log("id="+id);
          for (int i = 0; i < basementListBag.Count; i++)
          {
              if (basementListBag[i].name == id)
              {
                  this.transform.parent.GetComponent<CombineUI>().ChangeSelectedObject(basementListBag[i], null);
              }
          }
      }*/
    EventArgs BagToBench(object sender, EventArgs e)
    {
   //     if ((e as ItemMapArgs).UserName != CombineUI.Instance.UserName) return null;
        RefreshBag(bagCurrentPage);
        //      CombineUI.Instance.ChangeSelectedObject(itemsList[0]);
        return null;
    }
    EventArgs BenchToBag(object sender,EventArgs e)
    {
    //    if ((e as ItemMapArgs).UserName != CombineUI.Instance.UserName) return null;
        RefreshBag(1);
  //      CombineUI.Instance.ChangeSelectedObject(itemsList[0]);
        return null;
    }
        /// <summary>
    /// 
    /// </summary>
    /// <param name="page"></param>
    /// <returns>当前页码<returns>
    void RefreshBag(int page)
    {
    //    GetComponentInParent<CombineUI>().ChangeSelectedObject(null);
        var items = GameMapManager.Get<IBagManager>(CombineUI.Instance.UserName).ItemsInBag;
        bagTotalPage = ((items.Count + bagCntInRow - 1) / bagCntInRow);
        if (bagTotalPage < 1) bagTotalPage = 1;
        if (page < 1 )
        {
            page = 1;
        }
        if (page > bagTotalPage)
        {
            page = bagTotalPage;
        }
        int res, bgpos;
        if (items.Count == 0)
        {
            bgpos = 0;
            res = 0;
        }
        else
        {
            res = items.Count % bagCntInRow;
            if (res == 0) res = bagCntInRow;
            bgpos = res - 1;
            if (page < bagTotalPage)
            {
                res = bagCntInRow;
                bgpos += (bagTotalPage - page) * bagCntInRow;
            }
        }


        for (int i = bgpos, tot = 1; tot <= bagCntInRow; i--, tot++)
        {
            if (tot <= res)
            {
                BagItemsList[tot-1]=new Tuple<GameObject, CombinableItemField> (BagItemsList[tot-1].Item1,items[i]);
            }
            else
            {
                BagItemsList[tot-1]=new Tuple<GameObject, CombinableItemField>(BagItemsList[tot-1].Item1,null);
            }
        }

    //    Debug.Assert(itemsInCurrentPage.Count == itemsList.Count);
        for (int i = 0; i < BagItemsList.Count; i++)
        {
     //       BagItemsList[i].Item1.GetComponentInChildren<ObjectBasement>().ItemField = BagItemsList[i].Item2;
            if (BagItemsList[i].Item2 != null)
            {
                BagItemsList[i].Item1.transform.Find("Image").GetComponent<Image>().sprite =
                GameControl.GameManager.Get<GameControl.IItemInstantiateManager>().
            GetItemSettingByName((BagItemsList[i].Item2.ItemName.Split('_')[0])).GetComponentInChildren<SpriteRenderer>().sprite;

                BagItemsList[i].Item1.transform.eulerAngles = new Vector3(0, 0, BagItemsList[i].Item2.MeshTransform.MeshRotate*90);
                BagItemsList[i].Item1.transform.localScale = new Vector3(BagItemsList[i].Item2.MeshTransform.IsFlipedInMesh ? -1 : 1, 1, 1);
            }
            else
            {
                BagItemsList[i].Item1.transform.Find("Image").GetComponent<Image>().sprite = null;
            }

        }
        pageText.text = page + "/" + bagTotalPage;
        bagCurrentPage = page;
    }
    /// <summary>
    /// 生成背包上的网格
    /// </summary>
    void GenBagTable()
    {
        bagCurrentPage = 1;
        var pannelTrans = BagItemsList[0].Item1.transform.parent;
        //   Debug.Log((pannelTrans.GetComponent<RectTransform>().rect.width - gridBag.padding.left));
        bagCntInRow = Mathf.FloorToInt((pannelTrans.GetComponent<RectTransform>().rect.width - gridBag.padding.left) / (gridBag.padding.right + gridBag.cellSize.x));
        BagItemsList[0].Item1.name = "bag_1";
      //  basementListBag[0].GetComponentInChildren<Button>().onClick.SetListener(() => { BagObjectOnClick("bag_1"); });
        for (int i = 2; i <= bagCntInRow; i++)
        {
            var tp = GameObject.Instantiate(BagItemsList[0].Item1, gridBag.transform);
            tp.name = "bag_" + i;
            BagItemsList.Add(new Tuple<GameObject, CombinableItemField>(tp,null));
       ///     tp.GetComponentInChildren<Button>().onClick.SetListener(() => {BagObjectOnClick(tp.name); });
        }
        RefreshBag(1);
    }
}
